package com.lagou.config;

import com.lagou.io.Resource;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author: lcz
 * @date: Created in 13:58 2020/9/25
 * @description:
 */
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration pareConfig(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = document.getRootElement();
        //解析property子节点
        List<Element> elementList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        elementList.forEach(element -> {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        });

        //c3p0连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        //configuration 赋值
        configuration.setDataSource(dataSource);

        //解析mapper部分
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        //创建解析mapper中子节点的对象
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        //遍历所有的mapper节点
        for (Element mapper : mapperList) {
            String path = mapper.attributeValue("resource");
            InputStream stream = Resource.getResourceAsStream(path);
            //解析mapper中的子节点,并赋值给configuration对象中mappedStatementMap属性
            xmlMapperBuilder.parse(stream);
        }
        return configuration;
    }
}
